/**
 * @description 提供权限管理功能
 */
import { computed } from 'vue'
import { TOKEN_KEY, UID_KEY } from '@/constants/auth'

const MODE = import.meta.env.VITE_MODE

const DomainMap = {
  development: '.demo.cn',
  production: '.demo.com'
}

export function useAuth() {
  const cookieToken = useCookie(TOKEN_KEY, { domain: DomainMap[MODE] })
  const cookieUID = useCookie(UID_KEY, { domain: DomainMap[MODE] })
  const userInfo = useUserInfo()

  const getToken = () => {
    return cookieToken.value
  }

  const setToken = (token) => {
    cookieToken.value = token
  }

  const removeToken = () => {
    cookieToken.value = undefined
  }

  const getUid = () => {
    return cookieUID.value
  }

  const setUid = (uid) => {
    cookieUID.value = uid
  }

  const removeUid = () => {
    cookieUID.value = undefined
  }

  const isLogin = computed(() => {
    return Boolean(cookieToken.value && cookieUID.value && Object.keys(userInfo.value || {}).length)
  })

  const isRequest = computed(() => {
    return Boolean(cookieToken.value && cookieUID.value)
  })

  return {
    getToken,
    setToken,
    removeToken,
    getUid,
    setUid,
    removeUid,
    isLogin: isLogin,
    isRequest: isRequest
  }
}
